package cn.edu.scau.cmi.chenyuanying.safedComposite;

import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ResourceBundle;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.TextField;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;


public class SafedCompositeController implements Initializable {
	@FXML private TextField inputName;
	@FXML private ChoiceBox<String> teamChoiceBox;
	@FXML private TreeView<String> orgTreeView;
	@FXML private Button personButton;
	@FXML private Button teamButton;
	@FXML private Button deleteButton;
	private TreeItem<String> rootNode;
	private Team org;	// 组织
	
	private String name; 
	private String team; 
	private String init = "组织";
	private List<String> nameList; // 名字表
	private List<String> teamList; // 团队列表
	private ObservableList<String> obList;
	private ChangeListener<Number> choiceBoxListener;
	private List<String> deleteTargetList;
	private boolean isRoot;
	
	@Override
	public void initialize(URL location, ResourceBundle resources) {
		team = null; 
		teamList = new ArrayList<String>();
		teamList.add(init);
		nameList = new ArrayList<String>();
		nameList.add(init);
		// 初始化选择框
		choiceBoxListener = new ChangeListener<Number>() {
			@Override
			public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
				team = teamList.get(newValue.intValue());
				
			}
		};
		obList = FXCollections.observableArrayList(teamList);
		teamChoiceBox.getSelectionModel().selectedIndexProperty().addListener(choiceBoxListener);
		teamChoiceBox.setItems(obList);
		refresh();
		// 往TreeView中添加最开始的结点
		rootNode = new TreeItem<String>(init);
		rootNode.setExpanded(true);
		orgTreeView.setRoot(rootNode);
		
		// 为TreeNode增加监听器 获取点击的item 
		deleteTargetList = new ArrayList<String>();
		isRoot = false;
		orgTreeView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<TreeItem<String>>() {
			@Override
			public void changed(ObservableValue<? extends TreeItem<String>> observable, TreeItem<String> oldValue,
					TreeItem<String> newValue) {
				deleteTargetList.clear();
				isRoot = false;
				getAllChildrenName(newValue);
				if(newValue.equals(rootNode)) isRoot = true;
			}
		});
	}
	
	public void addPerson(ActionEvent e) {
		getInputInfo();
		if(!verifyInput()) {
			refresh();
			return;
		}
		TreeItem<String> treeNode = new TreeItem<String>(name);
		// 往TreeView中添加
		putInTreeView(rootNode, treeNode, team);
		// 往组织中添加
		Organization node = new Person(name);
		putInList(org, node, team);
		nameList.add(node.getName());
		refresh();
	}
	
	public void addTeam(ActionEvent e) {
		getInputInfo();
		if(!verifyInput()) {
			refresh();
			return;
		}
		Organization node = new Team(name);
		TreeItem<String> treeNode = new TreeItem<String>(name);
		treeNode.setExpanded(true);
		// 往TreeView中添加
		putInTreeView(rootNode, treeNode, team);
		// 往组织中添加
		putInList(org, node, team);		
		// 将新的团队添加到 TeamList表中 以便在选择框中显示 并且刷新选择框
		obList.add(node.getName());
		teamList.add(node.getName());
		// 在添加了新的团队之后 要刷新选择框
		nameList.add(node.getName());
		refresh();
	}
	
	// 删除组织中的结点 和 TreeView中的结点
	public void deleteNode(ActionEvent e) {
		// 通过监听器获取要删除的结点 得到相应的名字串
		if(deleteTargetList.size() == 0) return;
		// 不允许删除 rootNode 弹窗警告
		if(isRoot) {
			Alert alert = new Alert(AlertType.WARNING);
			alert.setHeaderText(null);
			alert.setContentText("不允许删除");
			alert.show();
			return;
		}
		String str;
		for(int i = 0; i < deleteTargetList.size(); i++) {
			str = deleteTargetList.get(i);
			deleteInList(nameList, str);
			deleteInList(obList, str);
			deleteInList(teamList, str);
		}
		deleteInTreeView(rootNode, deleteTargetList.get(0)); // 只要删除第一个 所有children都会被删除
	}

	// 获得一个结点下的所有结点的名字 放入deleteTargetList中
	private void getAllChildrenName(TreeItem<String> root) {
		deleteTargetList.add(root.getValue());
		for(TreeItem<String> item : root.getChildren()) {
			getAllChildrenName(item);
		}
	} 
	
	// 在TreeView中删除某一个Organization
	private boolean deleteInTreeView(TreeItem<String> root, String str) {
		ObservableList<TreeItem<String>> children = root.getChildren();
		if(children.size() > 0) {
			for(int i = 0; i < children.size(); i++) {
				if(children.get(i).getValue().compareTo(str) == 0) {
					children.remove(i);
					return true;
				}
				boolean res = deleteInTreeView(children.get(i), str);
				if(res) return true;
			}
		}
		return false;
	}
	
	// 在List中删除某一个Organization
	private void deleteInList(List<String> list, String str) {
		for(int i = 0; i < list.size(); i++) {
			if(list.get(i).compareTo(str) == 0) {
//				System.out.println("remove = " + list.get(i));
				list.remove(i);
				break;
			}
		}		
	}
	
	// 获取输入框和选择框的信息 name 和 team
	private void getInputInfo() {
		name = inputName.getText();
		team = teamChoiceBox.getSelectionModel().getSelectedItem();
	}
		
	// 往组织中添加结点 pre为node的上一个结点
	private boolean putInList(Organization preNode, Organization node, String pre) {
		if(preNode instanceof Team) {
			Team team = (Team)preNode;
			if(team.getName().compareTo(pre) == 0) {
				team.add(node);
				return true;
			}
			Iterator<Organization> itor = team.elements();
			while(itor.hasNext()) {
				Organization child = itor.next();
				boolean res = putInList(child, node, pre);
				if(res) return true;
			}
		}
		return false;
	}
	
	// 往TreeView中添加相应的结点 pre为node的上一个结点
	private boolean putInTreeView(TreeItem<String> preNode, TreeItem<String> node, String pre) {
		if(preNode.getValue().compareTo(pre) == 0) {
			preNode.getChildren().add(node);
			return true;
		}
		ObservableList<TreeItem<String>> childList = preNode.getChildren();
		for(TreeItem<String> item : childList) {
			boolean res = putInTreeView(item, node, pre);
			if(res) return false;
		}
		return false;
	}
	
	// 点击按钮之后刷新选择框和输入框	
	private void refresh() {
		inputName.clear();
		teamChoiceBox.getSelectionModel().selectFirst();
	}
	
	// 判断输入合法 并且不允许有重复的名字
	private boolean verifyInput() {
		String str = name;
		if(str == null || str.length() == 0) {
			// 输入不合法 弹出窗口提示
			Alert alert = new Alert(AlertType.WARNING);
			alert.setHeaderText(null);
			alert.setContentText("输入不合法");
			alert.show();
			return false;			
		} else {
			// 根据nameList 判断是否有名字重复
			for(String s : nameList) {
				if(s.compareTo(str) == 0) {
					Alert alert = new Alert(AlertType.WARNING);
					alert.setHeaderText(null);
					alert.setContentText("不允许重复的名字");
					alert.show();
					return false;
				}
			}			
		}
		return true;
	}

}
